<template>
  <div class="space-y-6">
    <div class="flex items-center justify-between">
      <div>
        <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-800">批量导入</h2>
        <p class="mt-1 text-sm text-gray-500">通过Excel文件批量导入植物数据</p>
      </div>
      <button class="text-gray-500 hover:text-gray-700 transition-custom" @click="$router.push('/plants')">
        <i class="fa fa-times text-xl"></i>
      </button>
    </div>

    <div class="bg-white rounded-xl shadow-custom p-6">
      <div class="mb-6">
        <div class="flex items-center p-4 mb-4 text-sm text-yellow-700 bg-yellow-100 rounded-lg" role="alert">
          <i class="fa fa-exclamation-circle mr-3"></i>
          <div>
            <p>请按照模板格式准备Excel文件，确保数据格式正确。模板可通过以下链接下载：</p>
            <a href="#" class="text-primary hover:underline transition-custom" @click="downloadTemplate">下载导入模板</a>
          </div>
        </div>
      </div>

      <div 
        class="border-2 border-dashed border-gray-300 rounded-xl p-8 text-center hover:border-primary transition-custom"
        :class="{ 'border-primary': isDragging }"
        @dragenter.prevent="isDragging = true"
        @dragleave.prevent="isDragging = false"
        @dragover.prevent
        @drop.prevent="handleFileDrop"
      >
        <div class="space-y-4">
          <div class="flex items-center justify-center">
            <i class="fa fa-file-excel text-5xl" :class="selectedFile ? 'text-success' : 'text-primary'"></i>
          </div>
          <h3 class="text-lg font-medium text-gray-800">
            {{ selectedFile ? selectedFile.name : '拖放Excel文件到此处' }}
          </h3>
          <p class="text-sm text-gray-500">或</p>
          <label class="inline-flex items-center justify-center px-5 py-3 border border-gray-300 shadow-sm text-base font-medium rounded-lg text-gray-700 bg-white hover:bg-gray-50 transition-custom cursor-pointer">
            <i class="fa fa-upload mr-2"></i>
            <span>选择文件</span>
            <input 
              type="file" 
              class="hidden" 
              accept=".xlsx, .xls"
              @change="handleFileSelect"
            >
          </label>
          <p class="text-xs text-gray-500">支持 .xlsx, .xls 格式文件</p>
        </div>
      </div>

      <!-- 数据预览 -->
      <div v-if="previewData.length > 0" class="mt-6">
        <h3 class="text-lg font-medium text-gray-800 mb-4">数据预览</h3>
        <div class="overflow-x-auto">
          <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
              <tr>
                <th v-for="header in tableHeaders" :key="header" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  {{ header }}
                </th>
              </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
              <tr v-for="(row, index) in previewData.slice(0, 5)" :key="index" class="hover:bg-gray-50">
                <td v-for="(value, key) in row" :key="key" class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                  {{ value }}
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="mt-4 text-sm text-gray-500">
          显示前5条数据，共 {{ previewData.length }} 条记录
        </div>
      </div>

      <div class="mt-6">
        <h3 class="text-lg font-medium text-gray-800 mb-4">导入说明</h3>
        <ul class="space-y-2 text-sm text-gray-600">
          <li class="flex items-start">
            <i class="fa fa-check-circle text-success mt-1 mr-2"></i>
            <span>Excel文件第一行为表头，必须包含：植物名称、学名、类别、分布地区等字段</span>
          </li>
          <li class="flex items-start">
            <i class="fa fa-check-circle text-success mt-1 mr-2"></i>
            <span>每行代表一条植物记录，字段顺序需与模板一致</span>
          </li>
          <li class="flex items-start">
            <i class="fa fa-check-circle text-success mt-1 mr-2"></i>
            <span>文件大小不能超过10MB</span>
          </li>
          <li class="flex items-start">
            <i class="fa fa-check-circle text-success mt-1 mr-2"></i>
            <span>导入过程中请勿刷新页面</span>
          </li>
        </ul>
      </div>

      <div class="mt-6 flex justify-end space-x-3">
        <button 
          class="px-6 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-custom"
          @click="$router.push('/plants')"
        >
          取消
        </button>
        <button 
          class="px-6 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-custom"
          :disabled="!selectedFile || isUploading"
          @click="handleImport"
        >
          <i class="fa fa-spinner fa-spin mr-2" v-if="isUploading"></i>
          <span>{{ isUploading ? '导入中...' : '开始导入' }}</span>
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import * as XLSX from 'xlsx'

export default {
  name: 'BatchImport',
  data() {
    return {
      isDragging: false,
      selectedFile: null,
      isUploading: false,
      previewData: [],
      tableHeaders: [],
      requiredFields: [
        '植物名称',
        '学名',
        '类别',
        '分布地区',
        '形态特征',
        '生态习性',
        '经济价值',
        '药用价值'
      ]
    }
  },
  methods: {
    handleDragEnter(e) {
      e.preventDefault()
      this.isDragging = true
    },
    handleDragLeave(e) {
      e.preventDefault()
      this.isDragging = false
    },
    handleFileDrop(e) {
      this.isDragging = false
      const file = e.dataTransfer.files[0]
      if (this.validateFile(file)) {
        this.selectedFile = file
        this.readExcelFile(file)
      }
    },
    handleFileSelect(e) {
      const file = e.target.files[0]
      if (this.validateFile(file)) {
        this.selectedFile = file
        this.readExcelFile(file)
      }
    },
    validateFile(file) {
      if (!file) return false

      // 检查文件类型
      const validTypes = [
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      ]
      if (!validTypes.includes(file.type)) {
        this.$message.error('请上传Excel文件(.xlsx或.xls格式)')
        return false
      }

      // 检查文件大小（10MB）
      if (file.size > 10 * 1024 * 1024) {
        this.$message.error('文件大小不能超过10MB')
        return false
      }

      return true
    },
    readExcelFile(file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const data = new Uint8Array(e.target.result)
          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheet = workbook.Sheets[workbook.SheetNames[0]]
          const jsonData = XLSX.utils.sheet_to_json(firstSheet)
          
          if (jsonData.length === 0) {
            this.$message.error('Excel文件内容为空')
            return
          }

          // 验证必填字段
          const headers = Object.keys(jsonData[0])
          const missingFields = this.requiredFields.filter(field => !headers.includes(field))
          
          if (missingFields.length > 0) {
            this.$message.error('缺少必填字段: ' + missingFields.join(', '))
            return
          }

          this.tableHeaders = headers
          this.previewData = jsonData
        } catch (error) {
          console.error('解析Excel文件失败:', error)
          this.$message.error('解析Excel文件失败，请检查文件格式是否正确')
        }
      }
      reader.readAsArrayBuffer(file)
    },
    async handleImport() {
      if (!this.selectedFile || this.previewData.length === 0) {
        this.$message.warning('请先选择要导入的Excel文件')
        return
      }

      try {
        this.isUploading = true
        // 这里应该调用后端API进行数据导入
        await new Promise(resolve => setTimeout(resolve, 2000)) // 模拟API调用
        
        this.$message.success('成功导入 ' + this.previewData.length + ' 条数据')
        this.$router.push('/plants')
      } catch (error) {
        console.error('导入失败:', error)
        this.$message.error('导入失败，请重试')
      } finally {
        this.isUploading = false
      }
    },
    downloadTemplate() {
      // 这里应该提供模板下载链接
      const templateUrl = '/templates/plant-import-template.xlsx'
      window.open(templateUrl, '_blank')
    }
  }
}
</script>

<style scoped>
.transition-custom {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.shadow-custom {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}
</style> 